import Vue from 'vue'
import Vuex from 'vuex'
import http from '../http'
import VuexPersistence from 'vuex-persist'

Vue.use(Vuex)
//持久化存储
const vuexLocal = new VuexPersistence({
  storage: window.localStorage,
  reducer: (state) => ({cateList: state.cateList}),
})

export default new Vuex.Store({
  state: {
    //频道分类数组
    cateList:[]
  },
  mutations: {
    initData(state,list){
      //给每一个item动态的添加属性 判断是否选中
      list.forEach(item => {
        Vue.set(item,"selected",true)
      });
      let storage = JSON.parse(localStorage.getItem('vuex'))
      if(storage && storage.cateList){
        state.cateList=storage.cateList
        return
      }
      state.cateList=list
    },
    changeState(state,id){
      state.cateList.forEach(item=>{
        if(item.id == id){
          item.selected = !item.selected
          return
        }
      })
    }
  },
  actions: {
    getData({commit}){
      http('/getCategroy',"get").then(res=>{
        // console.log(123)
        // console.log(res)
        commit("initData",res.result)
      }).catch(err=>{
        console.log(err)
      })
    }
  },
  getters:{
    getSelectedCate(state){
      return state.cateList.filter(item=>{
        return item.selected == true
      })
    },
    getUnSelectedCate(state){
      return state.cateList.filter(item=>{
        return item.selected == false
      })
    }
  },
  modules: {
  },
  plugins: [vuexLocal.plugin]
})
